package com.example.taobaounion.presenter.impl;

import com.example.taobaounion.model.Api;
import com.example.taobaounion.model.bean.Categories;
import com.example.taobaounion.presenter.IHomePresenter;
import com.example.taobaounion.utils.LogUtils;
import com.example.taobaounion.utils.RetrofitManager;
import com.example.taobaounion.view.IHomeCallback;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class HomePresenterImpl implements IHomePresenter {
    private IHomeCallback mCallback=null;

    @Override
    public void getCategories() {

        if(mCallback!=null){
            mCallback.onLoading();
        }
        //加载分类数据
        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        Api api = retrofit.create(Api.class);
        Call<Categories> task = api.getCategories();
        task.enqueue(new Callback<Categories>() {
            @Override
            public void onResponse(Call<Categories> call, Response<Categories> response) {
                //数据结果
                int code=response.code();
                LogUtils.d(HomePresenterImpl.this,"result code is --->"+code);
                if(code== HttpURLConnection.HTTP_OK){
                    //请求成功
                    Categories categories = response.body();
                    LogUtils.d(HomePresenterImpl.this,categories.toString());
                    if(mCallback!=null){
                        if (categories==null||categories.getData().size()==0) {
                            mCallback.onEmpty();
                        }else {
                            //把数据加载给UI
                            mCallback.onCategoriesLoaded(categories);
                        }
                    }
                }else {
                    //请求失败
                    LogUtils.d(HomePresenterImpl.this,"请求失败。。。。");
                    if (mCallback==null) {
                        mCallback.onError();
                    }
                }

            }

            @Override
            public void onFailure(Call<Categories> call, Throwable t) {
                //加载失败的结果
                LogUtils.d(HomePresenterImpl.this,"请求错误....");
                if (mCallback!=null) {
                    mCallback.onError();
                }
            }
        });
    }

    //把数据通知到UI
    //如果多个地方需要则用集合进行保存，例如喜马拉雅的播放，多个界面状态同时
    @Override
    public void registerViewCallback(IHomeCallback callback) {
         this.mCallback=callback;
    }

    @Override
    public void unregisterViewCallback(IHomeCallback callback) {

        this.mCallback=null;
    }
}
